//
//  PreviewImageView.swift
//  FreeWallpaperSwiftUI
//
//  Created by 张少康 on 2023/11/28.
//

import SwiftUI
import Kingfisher

struct PreviewImageView: View {
    
    var namespace: Namespace.ID
    
    var model: WallpaperItemModel
    
    @State private var showAlert = false
    
    var body: some View {
        ZStack  {
            Color.black.ignoresSafeArea()
            ZStack(alignment: .bottom) {
                KFImage(URL(string: "https://cn.bing.com" + (model.url ?? "")))
                    .resizable()
                    .loadDiskFileSynchronously()
                    .aspectRatio(16/9, contentMode: .fit)
                    .clipped()
                    .matchedGeometryEffect(id: (model.url ?? ""), in: namespace)
                
            }
            VStack (alignment: .leading){
                Spacer()
                HStack {
                    Text(model.title ?? "").font(.body).foregroundStyle(.white)
                    Spacer()
                }
                Text(model.copyright ?? "").font(.footnote).foregroundStyle(.white)
                    .padding(.bottom,12)
            }.padding(.horizontal)
            
            VStack{
                HStack {
                    Spacer()
                    Button(action:{
                        downloadAndSaveImage()
                    },label:{
                        Image(systemName: "arrow.down.app.fill").foregroundStyle(.white).font(.system(size: 22))
                    })
                }.padding(.horizontal)
                Spacer()
            }
            
            Text("图片保存成功.")
                .foregroundStyle(.white)
                .padding()
                .background(Color.black)
                .cornerRadius(10)
                .opacity(showAlert ? 1 : 0)
                .animation(.easeInOut(duration: 1.5),value: showAlert)
                .onAppear {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                        showAlert = false
                    }
                }
        }
    }
    
    func downloadAndSaveImage() {
        // 使用 Kingfisher 下载图片
        KingfisherManager.shared.retrieveImage(with:  URL(string:"https://cn.bing.com\(model.url ?? "")")!, options: [.cacheOriginalImage]) { result in
            switch result {
            case .success(let value):
                // 成功获取到图片后，将图片保存到相册
                saveImageToPhotoLibrary(image: value.image)
            case .failure(let error):
                print("Image download failed: \(error)")
            }
        }

    }
    
    func saveImageToPhotoLibrary(image: UIImage) {
        showAlert = true
        // 将图片保存到相册
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
    }
}

